package com.changgou.user.config;


import com.changgou.common.util.TokenDecode;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@EnableResourceServer
//需要使用security的相关注解进行授权鉴定的话，需要配置如下注解；可以在处理器的方法上面添加如：PreAuthorize
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    /**
     * 设置公钥的存储
     * @return 令牌信息存储对象
     */
    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter converter){
        return new JwtTokenStore(converter);
    }

    /**
     * 令牌转换器；主要设置在解析令牌的时候的公钥
     * @return
     */
    @Bean
    public JwtAccessTokenConverter converter(){
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //设置公钥
        converter.setVerifierKey(TokenDecode.getPubKey());
        return converter;
    }

    /**
     * 配置资源权限
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //除了以下的请求地址放行，其它的请求都需要认证之后才能访问
                //.antMatchers("/user/add","/user/load/*").permitAll()
                .antMatchers("/user/add").permitAll()
                .anyRequest().authenticated();
    }
}
